package org.wejde.muel;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * This class contains the members and methods related to
 * logging the event data locally.  The local log files are
 * named based on the filename provided with a suffix
 * corresponding to the current date added.  If the log
 * file exists, the data is added to the existing file.
 *  
 * @author Eric Martin
 * @author Webb Pinner
 *
 */
public class localLogClient {
	
	
	private String errorMsg;
	
	
	/**
	 * Date format to use when adding the suffix to the
	 * file.
	 */
	private static final String DATEFORMAT = "yyyy-MM-dd";
	
	/**
	 * The local log file to save the event data.  This
	 * value does include a path (absolute/relative) but
	 * does not include the date suffix.
	 */
	private String filename;

	/**
	 * Constructor method
	 * @param filename the local log file to save the event
	 * to.  This value also include either the absolute or
	 * relative path.
	 * 
	 */
	public localLogClient(String filename) {
		this.filename = filename;
		errorMsg = "";
	}

	/**
	 * Submit event text to be appended to the local logfile.
	 * 
	 * @param msg
	 * @return boolean flag designating the event was
	 * successfully written to the local logfile
	 */
	public boolean submitEvent(String msg) {
		// DEBUG
		//System.err.print("Local Log: " + msg);

		Date now = new Date();
		SimpleDateFormat fmt = new SimpleDateFormat(localLogClient.DATEFORMAT);

		String logfile = this.filename.split("\\.")[this.filename.split("\\.").length-2] + "_" + fmt.format(now) + "." + this.filename.split("\\.")[this.filename.split("\\.").length-1];
		try {
			BufferedWriter logwriter = new BufferedWriter(new FileWriter(logfile, true));
			logwriter.write(msg);
			logwriter.close();
			return true;
		} catch (IOException e) {
			//e.printStackTrace();
			//filename = null;
			this.errorMsg = "Error writing to local logfile: " + filename;
			return false;
		}
	}
	
	/**
	 * Return the last error message.
	 * 
	 * @return the error message as a String.
	 */
	public String getErrorMsg() {
		return this.errorMsg;
	}
}
